package com.example.traffic_learning;

import java.io.IOException;
import java.util.ArrayList;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;

import com.example.traffic_learning.FragStudy.ActivitySwipeDetector;

import global.MyArrayList;
import DTO.QuestionDTO;
import adapter.GridAdapterHistoryQuestion;
import adapter.HistoryQuestion;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.RelativeLayout.LayoutParams;

public class FragTest extends Fragment{
	
	private int questionNo = 30;
	private int currentQuestion = 0;
	private boolean isReview = false;
	private boolean isCorrect = false;
	private boolean isFinish = false;
	private int numOfCorrect = 0;
	
	private View view;
	private RelativeLayout myLayout;
	private View view1;
	
	private TextView textQuestionNumber;
	private TextView textQuestion;
	private CheckBox  checkAnswer1;
	private CheckBox  checkAnswer2;
	private CheckBox  checkAnswer3;
	private CheckBox  checkAnswer4;
	private ImageView imageViewQuestion;
	private static TextView textTimer;
	private static Activity activity;
	private AlertDialog alertDialogResult = null;
	
	private AlertDialog.Builder alertDialogBuilder;
	private ExpandableHeightGridView gridView;
	private AlertDialog alertDialog = null;
	private ArrayList<HistoryQuestion> listItem;
	private GridAdapterHistoryQuestion apdapter;
	
	
	ImageView image1;
	ImageView image2;
	ImageView image3;
	ImageView image4;
	ArrayList<QuestionDTO> questions;
	MyArrayList<ArrayList<UserAnswers>> listState;
	
	private long startTime = 0L;
	
	public static Handler customHandler = null;
	public static Runnable runnable = null;
	private GraphicalView mChartView = null;
	
	long timeInMilliseconds = 0L;
	long timeSwapBuff = 0L;
	long updatedTime = 0L;
	long totalTestTime = 0;
	long totalTestTimeSave = 0;
	String licenseType = null;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		super.onCreateView(inflater, container, savedInstanceState);
		activity = getActivity();
		view = inflater.inflate(R.layout.activity_test, container, false);
		//final View view1 = inflater.inflate(R.layout.custom_dialog_test, container, false);
		myLayout = (RelativeLayout)view.findViewById(R.id.layout_question_test);
		view1 = inflater.inflate(R.layout.custom_dialog_test, container, false);
		final View view2 = inflater.inflate(R.layout.grid_history_question, container, false);
		textQuestionNumber = (TextView)view.findViewById(R.id.text_question_number);
		
		listState = new MyArrayList<ArrayList<UserAnswers>>();
		
		imageViewQuestion = new ImageView(getActivity().getBaseContext());
		imageViewQuestion.setVisibility(View.INVISIBLE);
		
		textTimer = (TextView)view.findViewById(R.id.text_timer);
				
		image1 = (ImageView)view.findViewById(R.id.image_view_result_1_test);
		image2 = (ImageView)view.findViewById(R.id.image_view_result_2_test);
		image3 = (ImageView)view.findViewById(R.id.image_view_result_3_test);
		image4 = (ImageView)view.findViewById(R.id.image_view_result_4_test);
		
		myLayout.addView(imageViewQuestion);
		
		//MainActivity.timeTest = 300L * 1000L;
		Button btnNextQuestion = (Button)view.findViewById(R.id.button_next_question_test);
		btnNextQuestion.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				nextQuestion(view, view1, myLayout);
			}
		});
		
		Button btnPreviousQuestion = (Button)view.findViewById(R.id.button_previous_question_test);
		btnPreviousQuestion.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				previousQuestion(view, view1, myLayout);
			}
		});
		
		Button btnConclude = (Button)view.findViewById(R.id.button_conclude_question_test);
		btnConclude.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!isFinish){
					AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
					
					alertDialogBuilder.setMessage("Bạn có chắc muốn kết thúc bài thi không?")
							   .setCancelable(false)
							   .setPositiveButton("Có", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										isFinish = true;
										finishTest(view, view1, myLayout);
									}
							   })
							   .setNegativeButton("Không", new DialogInterface.OnClickListener() {
								
									@Override
									public void onClick(DialogInterface dialog, int which) {
										dialog.cancel();
									}
								});
					
					AlertDialog alertDialog = alertDialogBuilder.create();
					alertDialog.show();
				}else{
					finishTest(view, view1, myLayout);
				}
			}
		});
		Button buttonShowHistory = (Button)view.findViewById(R.id.button_show_history_test);
		buttonShowHistory.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				listItem = new ArrayList<HistoryQuestion>();
				showHistory(view, view2, myLayout);
			}
		});
		
		showChooseTest(view, view1, myLayout);
		
		RelativeLayout layoutStudy = (RelativeLayout)view.findViewById(R.id.layout_test);
		ScrollView scrollView = (ScrollView)view.findViewById(R.id.scroll_question_test);
		ActivitySwipeDetector activitySwipeDetector = new ActivitySwipeDetector();
		layoutStudy.setOnTouchListener(activitySwipeDetector);
		myLayout.setOnTouchListener(activitySwipeDetector);
		scrollView.setOnTouchListener(activitySwipeDetector);
		
		return view;
	}
	
	private void nextQuestion(View view, View view1, RelativeLayout myLayout){
		checkAnswer1.setEnabled(true);
		checkAnswer2.setEnabled(true);
		checkAnswer3.setEnabled(true);
		checkAnswer4.setEnabled(true);
		image1.setVisibility(View.INVISIBLE);
		image2.setVisibility(View.INVISIBLE);
		image3.setVisibility(View.INVISIBLE);
		image4.setVisibility(View.INVISIBLE);
		currentQuestion++;
		if(currentQuestion < questionNo){
			loadQuestion(view, myLayout);
			loadSavedUserAnswer(currentQuestion);
			if(isReview){
				showReview(view, view1, currentQuestion);
			}
		}else{
			currentQuestion--;
			loadQuestion(view, myLayout);
			loadSavedUserAnswer(currentQuestion);
			if(isReview){
				showReview(view, view1, currentQuestion);
			}
		}
	}
	
	private void previousQuestion(View view, View view1, RelativeLayout myLayout){
		checkAnswer1.setEnabled(true);
		checkAnswer2.setEnabled(true);
		checkAnswer3.setEnabled(true);
		checkAnswer4.setEnabled(true);
		image1.setVisibility(View.INVISIBLE);
		image2.setVisibility(View.INVISIBLE);
		image3.setVisibility(View.INVISIBLE);
		image4.setVisibility(View.INVISIBLE);
		currentQuestion--;
		if(currentQuestion >= 0){
			loadQuestion(view, myLayout);
			loadSavedUserAnswer(currentQuestion);
			if(isReview){
				showReview(view, view1, currentQuestion);
			}
		}else{
			currentQuestion++;
			loadQuestion(view, myLayout);
			loadSavedUserAnswer(currentQuestion);
			if(isReview){
				showReview(view, view1, currentQuestion);
			}
		}
	}
	
	private void loadQuestion(final View view , RelativeLayout layout){
		 
		 for(int j = 0; j < questionNo; j++){
			 ArrayList<UserAnswers> listUserAnswers = new ArrayList<UserAnswers>();
			 for(int i = 0; i < questions.get(j).getAnswers().size(); i++){
				 listUserAnswers.add(new UserAnswers(questions.get(j).getAnswers().get(i).getID(), false));
			 }
			 listState.add(listUserAnswers, j);
		 }	
		 
		 textQuestion = (TextView)view.findViewById(R.id.text_view_question_content_test);
		 //ImageView imageResult = (ImageView)view.findViewById(R.id.image_view_result_1_study);
		 checkAnswer1 = (CheckBox)view.findViewById(R.id.checkbox_result_1_test);	 
		 checkAnswer2 = (CheckBox)view.findViewById(R.id.checkbox_result_2_test);
		 checkAnswer3 = (CheckBox)view.findViewById(R.id.checkbox_result_3_test);
		 checkAnswer4 = (CheckBox)view.findViewById(R.id.checkbox_result_4_test);
		 
		 if(questions.get(currentQuestion).getImagePath() != null){
			 
			 LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
					  RelativeLayout.LayoutParams.WRAP_CONTENT);
			 layoutParams.addRule(RelativeLayout.BELOW, textQuestion.getId());
			 imageViewQuestion.setLayoutParams(layoutParams);
			 imageViewQuestion.setPaddingRelative(dpToPx(10), dpToPx(5), dpToPx(5), dpToPx(10));

			 Drawable image = null;
			 try{
				 Options opts = new BitmapFactory.Options();
				 opts.inDensity = DisplayMetrics.DENSITY_MEDIUM;
				 image = Drawable.createFromResourceStream(getResources(), null, getActivity().getAssets().open(questions.get(currentQuestion).getImagePath()), null, opts);
				 //image = Drawable.createFromStream(getActivity().getAssets().open(questions.get(currentQuestion).getImagePath()), null);
			 }catch(IOException e){
				 
			 }
			 imageViewQuestion.setImageDrawable(image);
			 imageViewQuestion.setId(1000);
			 imageViewQuestion.setVisibility(View.VISIBLE);
			 
			 LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
				      											   RelativeLayout.LayoutParams.WRAP_CONTENT);
			 //test.addRule(RelativeLayout.RIGHT_OF, imageResult.getId());
			 layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			 layoutParams1.addRule(RelativeLayout.BELOW, imageViewQuestion.getId());
			 layoutParams1.leftMargin = dpToPx(20);
			 checkAnswer1.setLayoutParams(layoutParams1);
			 
			 LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(dpToPx(18), dpToPx(18));
			 layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			 layoutParams2.addRule(RelativeLayout.BELOW, imageViewQuestion.getId());
			 layoutParams2.topMargin = dpToPx(7);
			 layoutParams2.leftMargin = dpToPx(28);
			 image1.setLayoutParams(layoutParams2);
			 
		 }else{
			 imageViewQuestion.setVisibility(View.INVISIBLE);
			 LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
					   RelativeLayout.LayoutParams.WRAP_CONTENT);
			 //test.addRule(RelativeLayout.RIGHT_OF, imageResult.getId());
			 layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			 layoutParams1.addRule(RelativeLayout.BELOW, textQuestion.getId());
			 layoutParams1.leftMargin = dpToPx(20);
			 checkAnswer1.setLayoutParams(layoutParams1);
			 
			 LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(dpToPx(18), dpToPx(18));
			 layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			 layoutParams2.addRule(RelativeLayout.BELOW, textQuestion.getId());
			 layoutParams2.topMargin = dpToPx(7);
			 layoutParams2.leftMargin = dpToPx(28);
			 image1.setLayoutParams(layoutParams2);
		 }
		 
		 
		 
		 checkAnswer1.setVisibility(View.INVISIBLE);
		 checkAnswer2.setVisibility(View.INVISIBLE);
		 checkAnswer3.setVisibility(View.INVISIBLE);
		 checkAnswer4.setVisibility(View.INVISIBLE);
		 
		 checkAnswer1.setChecked(false);
		 checkAnswer2.setChecked(false);
		 checkAnswer3.setChecked(false);
		 checkAnswer4.setChecked(false);
		 //textQuestion.setVisibility(View.INVISIBLE);
		 textQuestion.setText(questions.get(currentQuestion).getContent());
		 textQuestionNumber.setText("CÂU " + (currentQuestion+1));
		 if(questions.get(currentQuestion).getAnswers().size() == 2){
			 checkAnswer1.setVisibility(View.VISIBLE);
			 checkAnswer1.setText(questions.get(currentQuestion).getAnswers().get(0).getContent());
			 checkAnswer1.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(checkAnswer1.isChecked()){
						listState.getElementByTag(currentQuestion).get(0).setChecked(true);
					}else{
						listState.getElementByTag(currentQuestion).get(0).setChecked(false);
					}
				}
			});
			 
			 checkAnswer2.setVisibility(View.VISIBLE);
			 checkAnswer2.setText(questions.get(currentQuestion).getAnswers().get(1).getContent());
			 checkAnswer2.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						if(checkAnswer2.isChecked()){
							listState.getElementByTag(currentQuestion).get(1).setChecked(true);
						}else{
							listState.getElementByTag(currentQuestion).get(1).setChecked(false);
						}
					}
				});
		 }else{
			 if(questions.get(currentQuestion).getAnswers().size() == 3){
				 checkAnswer1.setVisibility(View.VISIBLE);
				 checkAnswer1.setText(questions.get(currentQuestion).getAnswers().get(0).getContent());
				 checkAnswer1.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							if(checkAnswer1.isChecked()){
								listState.getElementByTag(currentQuestion).get(0).setChecked(true);
							}else{
								listState.getElementByTag(currentQuestion).get(0).setChecked(false);
							}
						}
					});
				 
				 checkAnswer2.setVisibility(View.VISIBLE);
				 checkAnswer2.setText(questions.get(currentQuestion).getAnswers().get(1).getContent());
				 checkAnswer2.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							if(checkAnswer2.isChecked()){
								listState.getElementByTag(currentQuestion).get(1).setChecked(true);
							}else{
								listState.getElementByTag(currentQuestion).get(1).setChecked(false);
							}
						}
					});
				 
				 checkAnswer3.setVisibility(View.VISIBLE);
				 checkAnswer3.setText(questions.get(currentQuestion).getAnswers().get(2).getContent());
				 checkAnswer3.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							if(checkAnswer3.isChecked()){
								listState.getElementByTag(currentQuestion).get(2).setChecked(true);
							}else{
								listState.getElementByTag(currentQuestion).get(2).setChecked(false);
							}
						}
					});
			 }else{
				 checkAnswer1.setVisibility(View.VISIBLE);
				 checkAnswer1.setText(questions.get(currentQuestion).getAnswers().get(0).getContent());
				 checkAnswer1.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							if(checkAnswer1.isChecked()){
								listState.getElementByTag(currentQuestion).get(0).setChecked(true);
							}else{
								listState.getElementByTag(currentQuestion).get(0).setChecked(false);
							}
						}
					});
				 
				 checkAnswer2.setVisibility(View.VISIBLE);
				 checkAnswer2.setText(questions.get(currentQuestion).getAnswers().get(1).getContent());
				 checkAnswer2.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							if(checkAnswer2.isChecked()){
								listState.getElementByTag(currentQuestion).get(1).setChecked(true);
							}else{
								listState.getElementByTag(currentQuestion).get(1).setChecked(false);
							}
						}
					});
				 
				 checkAnswer3.setVisibility(View.VISIBLE);
				 checkAnswer3.setText(questions.get(currentQuestion).getAnswers().get(2).getContent());
				 checkAnswer3.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							if(checkAnswer3.isChecked()){
								listState.getElementByTag(currentQuestion).get(2).setChecked(true);
							}else{
								listState.getElementByTag(currentQuestion).get(2).setChecked(false);
							}
						}
					});
				 
				 checkAnswer4.setVisibility(View.VISIBLE);
				 checkAnswer4.setText(questions.get(currentQuestion).getAnswers().get(3).getContent());
				 checkAnswer4.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							if(checkAnswer4.isChecked()){
								listState.getElementByTag(currentQuestion).get(3).setChecked(true);
							}else{
								listState.getElementByTag(currentQuestion).get(3).setChecked(false);
							}
						}
					});
			 }
		 }
	 }
	
	private class UserAnswers{
		private String AnswerID;
		private boolean isChecked;
		
		public UserAnswers(String answerID, boolean isChecked){
			this.AnswerID = answerID;
			this.isChecked = isChecked;
		}
		
		public String getAnswerID() {
			return AnswerID;
		}
		@SuppressWarnings("unused")
		public void setAnswerID(String answerID) {
			AnswerID = answerID;
		}
		@SuppressWarnings("unused")
		public boolean isChecked() {
			return isChecked;
		}
		public void setChecked(boolean isChecked) {
			this.isChecked = isChecked;
		}		 
	}
	
	private int dpToPx(int dp) {
	    DisplayMetrics displayMetrics = getActivity().getBaseContext().getResources().getDisplayMetrics();
	    int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));       
	    return px;
	}
	
	private void loadSavedUserAnswer(int curQuestion){
		 switch (listState.getElementByTag(curQuestion).size()) {
			case 2:
				checkAnswer1.setChecked(listState.getElementByTag(curQuestion).get(0).isChecked);
				checkAnswer2.setChecked(listState.getElementByTag(curQuestion).get(1).isChecked);
				break;
			case 3:
				checkAnswer1.setChecked(listState.getElementByTag(curQuestion).get(0).isChecked);
				checkAnswer2.setChecked(listState.getElementByTag(curQuestion).get(1).isChecked);
				checkAnswer3.setChecked(listState.getElementByTag(curQuestion).get(2).isChecked);
				break;
			case 4:
				checkAnswer1.setChecked(listState.getElementByTag(curQuestion).get(0).isChecked);
				checkAnswer2.setChecked(listState.getElementByTag(curQuestion).get(1).isChecked);
				checkAnswer3.setChecked(listState.getElementByTag(curQuestion).get(2).isChecked);
				checkAnswer4.setChecked(listState.getElementByTag(curQuestion).get(3).isChecked);
				break;

		 }
	 }
	private void finishTest(final View view, final View view1, final RelativeLayout layout){
		isFinish = true;
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
		
		alertDialogBuilder.setCancelable(false)
				   .setPositiveButton("Xem lại bài thi", new DialogInterface.OnClickListener() {
					
						@Override
						public void onClick(DialogInterface dialog, int which) {
							isReview = true;
							currentQuestion = 0;
							loadQuestion(view, layout);
							showReview(view, view1, currentQuestion);
						}
				   })
				   .setNegativeButton("Bỏ qua", new DialogInterface.OnClickListener() {
					
						@Override
						public void onClick(DialogInterface dialog, int which) {
							showDialogRetest(view, view1, layout);
							dialog.cancel();
						}
					});

		LinearLayout chartLayout = (LinearLayout)view1.findViewById(R.id.chart);
		TextView textView = (TextView)view1.findViewById(R.id.text_show_correct_number);
		int numCorrect = getNumOfCorrect(view);
		textView.setText("Bạn đã làm đúng " + numCorrect + "/" + questionNo +" câu");
		textView.setTextColor(Color.WHITE);
		String[] code = new String[] {
	            "Câu đúng", "Câu sai"
	        };
		
		Log.d("So cau dung", numCorrect + "");
		Log.d("% dung", ((double)numCorrect/(double)questionNo)*100 + "%");
	    // Pie Chart Section Value
	    double[] distribution = { numCorrect, questionNo - numCorrect } ;
	 
	    // Color of each Pie Chart Sections
	    int[] colors = { Color.GREEN, Color.RED };
	 
	    // Instantiating CategorySeries to plot Pie Chart
	    CategorySeries distributionSeries = new CategorySeries("");
	    for(int i=0 ;i < distribution.length;i++){
	        // Adding a slice with its values and name to the Pie Chart
	        distributionSeries.add(code[i], distribution[i]);
	    }
	 
	    // Instantiating a renderer for the Pie Chart
	    DefaultRenderer defaultRenderer  = new DefaultRenderer();
	    for(int i = 0 ;i<distribution.length;i++){
	        SimpleSeriesRenderer seriesRenderer = new SimpleSeriesRenderer();
	        seriesRenderer.setColor(colors[i]);
	        seriesRenderer.setDisplayChartValues(true);
	        seriesRenderer.setChartValuesTextSize(40);
	        // Adding a renderer for a slice
	        defaultRenderer.addSeriesRenderer(seriesRenderer);
	    }
	    defaultRenderer.setZoomButtonsVisible(true);
	    if(mChartView!= null){
	    	chartLayout.removeView(mChartView);
	    }
	    mChartView = null;
		mChartView = ChartFactory.getPieChartView(getActivity().getBaseContext(), distributionSeries , defaultRenderer);
		mChartView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, dpToPx(200)));
		
		chartLayout.addView(mChartView);
		/*if(isAddChart == false){
			chartLayout.addView(mChartView);
			isAddChart = true;
		}
		chartLayout.addView(mChartView);*/
		
		chartLayout.setBackgroundColor(Color.BLACK);
		alertDialogBuilder.setView(chartLayout);
		if(alertDialogResult == null){
			alertDialogResult = alertDialogBuilder.create();
		}
		alertDialogResult.show();
	}
	private void showReview(View view, View view1, int curQuestion){
		int i = 0;
		image1.setVisibility(View.INVISIBLE);
		image2.setVisibility(View.INVISIBLE);
		image3.setVisibility(View.INVISIBLE);
		image4.setVisibility(View.INVISIBLE);
		/*for(UserAnswers userAnswers : listState.getElementByTag(curQuestion)){
				
			for (CorrectAnswerDTO correctAnswer : questions.get(curQuestion).getCorrectAnswers()) {
				if(userAnswers.getAnswerID().equals(correctAnswer.getAnswerID()) && userAnswers.isChecked){
					setImageResult(view, i, true, false);
					break;
				}else{
					if(userAnswers.getAnswerID() != correctAnswer.getAnswerID() && userAnswers.isChecked){
						setImageResult(view, i, false, false);
					}else{
						if(userAnswers.getAnswerID().equals(correctAnswer.getAnswerID()) && !userAnswers.isChecked){
							setImageResult(view, i, false, true);
						}
					}
				}
			}
			i++;
		}*/
		/*boolean isChecked = false;
		for(UserAnswers userAnswers : listState.getElementByTag(curQuestion)){
			if(userAnswers.isChecked){
				isChecked = true;
				break;
			}
			
		}
		if(isChecked){*/
			ArrayList<String> ArrayAnswerCorrect = new ArrayList<String>();
			for(int j = 0; j < questions.get(curQuestion).getCorrectAnswers().size(); j++){
				ArrayAnswerCorrect.add(questions.get(curQuestion).getCorrectAnswers().get(j).getAnswerID());
			}
			for(UserAnswers userAnswers : listState.getElementByTag(curQuestion)){
				isCorrect = true;
				if(userAnswers.isChecked && ArrayAnswerCorrect.contains(userAnswers.getAnswerID())){
					setImageResult(view, i, true, false);
				}
				else{
					if(!userAnswers.isChecked && ArrayAnswerCorrect.contains(userAnswers.getAnswerID())){
						setImageResult(view, i, false, true);
					}
					if(userAnswers.isChecked && !ArrayAnswerCorrect.contains(userAnswers.getAnswerID())){
						setImageResult(view, i, false, false);
					}
				}
				i++;
			}
			
			checkAnswer1.setEnabled(false);
			checkAnswer2.setEnabled(false);
			checkAnswer3.setEnabled(false);
			checkAnswer4.setEnabled(false);
		//}
	}
	private void setImageResult(View view, int index, boolean isTrue, boolean isNoneCheck){
		 
		 switch(index){
		 	case 0:
		 		if(isTrue){
		 			image1.setImageResource(R.drawable.blue_tick);
		 		}else{
		 			if(isNoneCheck){
		 				image1.setImageResource(R.drawable.red_tick);
		 			}else{	
		 				image1.setImageResource(R.drawable.red_x);
		 			}
		 		}
		 		image1.setVisibility(View.VISIBLE);
		 		checkAnswer1.setChecked(false);
		 		break;
		 	case 1:
		 		if(isTrue){
		 			image2.setImageResource(R.drawable.blue_tick);
		 		}else{
		 			if(isNoneCheck){
		 				image2.setImageResource(R.drawable.red_tick);
		 			}else{	
		 				image2.setImageResource(R.drawable.red_x);
		 			}
		 		}
		 		image2.setVisibility(View.VISIBLE);
		 		checkAnswer2.setChecked(false);
		 		break;
		 	case 2:
		 		if(isTrue){
		 			image3.setImageResource(R.drawable.blue_tick);
		 		}else{
		 			if(isNoneCheck){
		 				image3.setImageResource(R.drawable.red_tick);
		 			}else{	
		 				image3.setImageResource(R.drawable.red_x);
		 			}
		 		}
		 		image3.setVisibility(View.VISIBLE);
		 		checkAnswer3.setChecked(false);
		 		break;
		 	case 3:
		 		if(isTrue){
		 			image4.setImageResource(R.drawable.blue_tick);
		 		}else{
		 			if(isNoneCheck){
		 				image4.setImageResource(R.drawable.red_tick);
		 			}else{	
		 				image4.setImageResource(R.drawable.red_x);
		 			}
		 		}
		 		image4.setVisibility(View.VISIBLE);
		 		checkAnswer4.setChecked(false);
		 		break;
		 }
	 }
	private int getNumOfCorrect(View view){
		numOfCorrect = 0;
		ArrayList<String> ArrayAnswerCorrect = new ArrayList<String>();
		for(int i = 0; i < questionNo ; i++){
			while(ArrayAnswerCorrect.size() > 0){
				ArrayAnswerCorrect.remove(0);
			}
			for(int j = 0; j < questions.get(i).getCorrectAnswers().size(); j++){
				ArrayAnswerCorrect.add(questions.get(i).getCorrectAnswers().get(j).getAnswerID());
			}
			for(UserAnswers userAnswers : listState.getElementByTag(i)){
				isCorrect = true;
				if(userAnswers.isChecked && ArrayAnswerCorrect.contains(userAnswers.getAnswerID())){
					isCorrect = true;
				}
				else{
					if(!userAnswers.isChecked && ArrayAnswerCorrect.contains(userAnswers.getAnswerID())){
						isCorrect = false;
						break;
					}
					if(userAnswers.isChecked && !ArrayAnswerCorrect.contains(userAnswers.getAnswerID())){
						isCorrect = false;
						break;
					}
				}
			}
			if(isCorrect){
				numOfCorrect++;
				Log.d("Cau dung", i + 1 + "");
			}
		}
		return numOfCorrect;
	}
	private void showTimeOut(final View view, final View view1, final RelativeLayout myLayout){
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
		
		alertDialogBuilder.setMessage("Hết giờ làm bài!")
				   .setCancelable(false)
				   .setPositiveButton("Đồng ý", new DialogInterface.OnClickListener() {
					
						@Override
						public void onClick(DialogInterface dialog, int which) {
							finishTest(view, view1, myLayout);
						}
				   });
		
		AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}
	
	private void showChooseTest(final View view, final View view1, final RelativeLayout myLayout){
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
		final ArrayAdapter<String> arrAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1);
		arrAdapter.add("GPLX Hạng A1 , A2");
		arrAdapter.add("GPLX Hạng A3, A4");
		arrAdapter.add("GPLX Hạng B1");
		arrAdapter.add("GPLX Hạng B2, C, D, E, F");
		alertDialogBuilder.setAdapter(arrAdapter, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch(which){
				case 0:
					licenseType = "A1";
					totalTestTime = 15*60;
					break;
				case 1:
					licenseType = "A3";
					totalTestTime = 15*60;
					break;
				case 2:
					licenseType = "B1";
					totalTestTime = 20*60;
					break;
				case 3:
					licenseType = "B2";
					totalTestTime = 20*60;
					break;
				}
				totalTestTimeSave = totalTestTime;
				getQuestion(view, view1, myLayout);
			}
		}).setCancelable(false);
		
		AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface arg0, int arg1, KeyEvent arg2) {
				getActivity().finish();
				return false;
			}
		});
		alertDialog.show();
	}
	public static void releaseHandler(){
		if(runnable != null && customHandler != null){
			customHandler.removeCallbacks(runnable);
			customHandler = null;
		}
	}
	
	private void showDialogRetest(final View view, final View view1, final RelativeLayout myLayout){
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
		
		alertDialogBuilder.setMessage("Bạn có muốn thi lại không?")
				   .setCancelable(false)
				   .setPositiveButton("Đồng ý", new DialogInterface.OnClickListener() {
					
						@Override
						public void onClick(DialogInterface dialog, int which) {
							checkAnswer1.setEnabled(true);
							checkAnswer2.setEnabled(true);
							checkAnswer3.setEnabled(true);
							checkAnswer4.setEnabled(true);
							image1.setVisibility(View.INVISIBLE);
							image2.setVisibility(View.INVISIBLE);
							image3.setVisibility(View.INVISIBLE);
							image4.setVisibility(View.INVISIBLE);
							listState = new MyArrayList<ArrayList<UserAnswers>>();
							getQuestion(view, view1, myLayout);
						}
				   })
				   .setNegativeButton("Thoát", new DialogInterface.OnClickListener() {
					
						@Override
						public void onClick(DialogInterface dialog, int which) {
							/*Intent intent = new Intent(getActivity(), MainMenu.class);
							startActivity(intent);*/
							getActivity().onBackPressed();
						}
				   });
		AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}
	private void getQuestion(final View view, final View view1, final RelativeLayout myLayout){
		currentQuestion = 0;
		releaseHandler();
		numOfCorrect = 0;
		isReview = false;
		//listState = new MyArrayList<ArrayList<UserAnswers>>();
		isFinish = false;
		totalTestTime = totalTestTimeSave;
		questions = QuestionDTO.RandomQuestionsByLicenseType(getActivity(), licenseType);
		questionNo = questions.size();
		loadQuestion(view, myLayout);
		timeInMilliseconds = 0L;
		timeSwapBuff = 0L;
		updatedTime = 0L;
		startTime = SystemClock.uptimeMillis();
		customHandler = new Handler();
		runnable = new Runnable() {
			public void run() {
				timeInMilliseconds = SystemClock.uptimeMillis() - startTime;	
				updatedTime = timeSwapBuff + timeInMilliseconds;
				int secs = (int)totalTestTime - (int) (updatedTime / 1000);
				if(!isFinish){				
					if(secs <= 3 * 60){
						textTimer.setTextColor(Color.RED);
					}
					if(secs == 0){
						try{
							showTimeOut(view, view1, myLayout);
						}catch(Exception e){}
					}
				}else{
					secs = 0;
				}
				int mins = secs / 60;
				secs = secs % 60;
				textTimer.setText("" + mins + ":" + String.format("%02d", secs));
				if(secs > 0 || mins >  0)
					customHandler.postDelayed(this, 1000);
			}
		};
		customHandler.postDelayed(runnable, 1000);
	}
	
	private void showHistory(final View view, View view1, final RelativeLayout myLayout){
		alertDialogBuilder = new AlertDialog.Builder(getActivity());
		alertDialogBuilder.setCancelable(false)
				   .setPositiveButton("Trở về", new DialogInterface.OnClickListener() {
					
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
				   });
		gridView = (ExpandableHeightGridView)view1.findViewById(R.id.expanable_gridview_history);
		Boolean isChecked = false;
		for(int i = 0; i < questions.size(); i++){
			if(listState.getElementByTag(i) != null){
				isChecked = false;
				for(int j = 0; j < listState.getElementByTag(i).size(); j++){
					if(listState.getElementByTag(i).get(j).isChecked){
						isChecked = true;
						break;
					}
				}
				HistoryQuestion historyQuestion = new HistoryQuestion();
				historyQuestion.setQuestionNo("Câu " + (i + 1));
				historyQuestion.setIsChecked(isChecked);
				historyQuestion.setIsTrue(false);
				listItem.add(historyQuestion);
			}
		}
		apdapter = new GridAdapterHistoryQuestion(getActivity().getBaseContext(), listItem);
		gridView.setAdapter(apdapter);
		gridView.setExpanded(true);
		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int index,
					long arg3) {
				currentQuestion = index;
				loadQuestion(view, myLayout);
				loadSavedUserAnswer(currentQuestion);
				if(alertDialog != null){
					alertDialog.dismiss();
				}
			}
		});

		ScrollView scrollView = (ScrollView)view1.findViewById(R.id.scroolView_history);
		try{
			alertDialogBuilder.setView(scrollView);
		}catch(Exception e){}
		if(alertDialog == null)
			alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}
	public static void showDialog(){
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
		
		alertDialogBuilder.setMessage("Bạn có muốn thoát không?")
				   .setCancelable(false)
				   .setPositiveButton("Có", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						activity.finish();
						dialog.dismiss();
					}
				}).setNegativeButton("Không", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}
	
	class ActivitySwipeDetector implements View.OnTouchListener {

		static final String logTag = "ActivitySwipeDetector";
		static final int MIN_DISTANCE = 100;
		private float downX, downY, upX, upY;

		public boolean onTouch(View v, MotionEvent event) {
		    switch(event.getAction()){
		        case MotionEvent.ACTION_DOWN: {
		            downX = event.getX();
		            downY = event.getY();
		            return true;
		        }
		        case MotionEvent.ACTION_UP: {
		            upX = event.getX();
		            upY = event.getY();
		            float deltaX = downX - upX;
		            float deltaY = downY - upY;
			        if(Math.abs(deltaX) > Math.abs(deltaY)){
			            if(Math.abs(deltaX) > MIN_DISTANCE){
			                if(deltaX < 0) { 
			                	previousQuestion(view, view1, myLayout); 
			                	return true; 
			                }
			                if(deltaX > 0) { 
			                	nextQuestion(view, view1, myLayout); 
			                	return true; 
			                }
			            }
			        } 
		        }
		        return false;
		    }
			return false;
		}
	}
	
}
